<?php

namespace App\Models;

use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Facades\DB;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Support\Facades\Log;

class User extends Authenticatable implements JWTSubject
{
    use Notifiable;
    use SoftDeletes;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'password', 'phone', 'name', 'agency_id', 'type_id', 'status', 'openid'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * Get the identifier that will be stored in the subject claim of the JWT.
     *
     * @return mixed
     */
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    /**
     * Return a key value array, containing any custom claims to be added to the JWT.
     *
     * @return array
     */
    public function getJWTCustomClaims()
    {
        return [];
    }

    public function type()
    {
        return $this->belongsTo(Type::class);
    }

    public function agency()
    {
        return $this->belongsTo(Agency::class);
    }

    public function children()
    {
        return $this->hasMany(Child::class);
    }

    public function official()
    {
        return $this->hasOne(Official::class);
    }

    public function currentChild()
    {
        return $this->hasMany(CurrentChild::class);
    }

    public static function add($data)
    {
        DB::beginTransaction();
        try {
            /* 添加角色 */
            $data['password'] = bcrypt($data['password']);
            $user = User::create($data);
            if (!$user) {
                throw new \Exception('');
            }

            DB::commit();
            return true;
        } catch (\Exception $e) {
            Log::error($e->getMessage());
            DB::rollBack();
            return false;
        }
    }

    /**
     * 拼接查询条件
     *      */
    public static function selectQuery($data)
    {
        return function ($query) use ($data) {
            if (isset($data['agency_id']) && $data['agency_id'] > 0) {
                $query->where('agency_id', $data['agency_id']);
            }
            if (isset($data['name']) && !empty($data['name'])) {
                $query->where('name', 'like', '%' . $data['name'] . '%');
            }
            if (isset($data['phone']) && !empty($data['phone'])) {
                $query->where('phone', 'like', '%' . $data['phone'] . '%');
            }
        };
    }
}
